var express = require('express');
var router = express.Router();
var superagent = require('superagent');
var ItbUserModel = require('../../common/mysql/mapping/ItbUserModel');
var ItbPlatformUserModel = require('../../common/mysql/mapping/ItbPlatformUserModel');
var ItbDocumentModel = require('../../common/mysql/mapping/ItbDocumentModel');
var ItbCollectModel = require('../../common/mysql/mapping/ItbCollectModel');
var ItbFeedbackModel = require('../../common/mysql/mapping/ItbFeedbackModel');
var TgUserDocModel = require('../../common/mysql/mapping/TgUserDocModel');
var async  = require( 'async'); // 同步控制
var CONFIG = require('../../common/config');
var CODE = require('../../common/code');
var usersUtil = require('./util/usersUtil.js');
var checkUtil = require('./util/checkUtil.js');
var moment = require('moment');

var cacheManager = require('cache-manager');
var redisStore = require('cache-manager-redis');
var vcdRedisCache = cacheManager.caching({
  store: redisStore,
  host: CONFIG.VCODE_REDIS_SERVER_DOMAIN,
  port: CONFIG.VCODE_REDIS_SERVER_PORT,
  auth_pass: CONFIG.VCODE_REDIS_SERVER_PASSWORD,
  db: CONFIG.VCODE_REDIS_SERVER_DB_NUMBER,
  ttl: CONFIG.VCODE_REDIS_SERVER_TTL,
  //prefix: CONFIG.VCODE_REDIS_SERVER_PREFIX // cache-manager-redis@0.3.2依赖cache-manager@2.2.0时有bug导致prefix无效；cache-manager-redis@0.3.2依赖cache-manager@2.9.0时prefix有效
});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

//------------------------------------------------------------------
//------------------------------------------------------------------
/* 用手机号注册.
 * 方式:POST
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:mobile:手机号
 * 参数:password:MD5加密的密码
 * 参数:code:验证码
 * 参数: uuid: 设备标识符
 *
 * 测试地址：http://localhost:3000/users/regist?password=123456&mobile=13344445555&uuid=000
 * */
function regist(req, res, next) {
  // get parameter
  var password = req.body.password || req.query.password;
  var mobile = req.body.mobile || req.query.mobile;
  var uuid = req.body.uuid || req.query.uuid;

  // return function
  function ret_func(success,msg, user_id){
    var obj = {
      success:success,
      msg:msg,
      data: {
        user_id:user_id,
      }
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof password=='undefined' ){
    return ret_func(0,CODE.PASSWORD_EMPTY);
  }
  if(typeof mobile=='undefined'){
    return ret_func(0,CODE.MOBILE_EMPTY);
  }
  if(typeof uuid=='undefined'){
    return ret_func(0,CODE.UUID_EMPTY);
  }

  var chkEntity = new ItbUserModel({
    mobile: mobile,
    del_flg: 0
  });
  chkEntity.findFromDB(function(err, items){
    if(err){
      console.log('user.js regist check error:'+err);
      return ret_func(0,CODE.CREATE_USER_ERROR);
    }

    if (items != null && items.length > 0) {
      // 已注册过
      console.log('user.js regist user exist');
      return ret_func(0,CODE.CREATE_USER_EXIST);
    } else {
      // 新建
      var entity = new ItbUserModel({
        password  :password,
        mobile    :mobile,
        uuid      :uuid,
        user_type :1,
      });
      entity.saveToDB(function(error, id){
        // process error
        if(error){
          console.log('user.js regist error:'+error);

          return ret_func(0,CODE.CREATE_USER_ERROR);
        }
        // process success
        return ret_func(1,CODE.OPERATION_SUCCESS,id);
      });
    }
  });

}
router.get('/regist', regist);
router.post('/regist', regist);

//------------------------------------------------------------------
/* 其他登录.
 * 方式:POST
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数: wxuid:微信的 uid
 * 参数: uuid: 设备标识符
 * 参数: mobile : 手机号(可选)
 * */
function otherLogin(req, res, next) {
  var obj = {
    success:1,msg:'success',
    "data": {
      user_id:1234123123123,

    }

  };
  res.set('Content-Type', 'application/json');
  res.json(obj);
}
router.get('/otherLogin', otherLogin);
router.post('/otherLogin', otherLogin);

//------------------------------------------------------------------
/* 用手机号登陆.
 * 方式:POST
 * 参数:pc: 1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:mobile: 手机号
 * 参数:password: MD5加密的密码
 * 参数:uuid: 设备标识符
 * */
function login(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var password = req.body.password || req.query.password;
  var mobile = req.body.mobile || req.query.mobile;
  var uuid = req.body.uuid || req.query.uuid;// TODO

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data||{}
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof password=='undefined' || password == null || password.trim().length == 0){
    return ret_func(0,CODE.PASSWORD_EMPTY);
  }
  if(typeof mobile=='undefined' || mobile == null){
    return ret_func(0,CODE.MOBILE_EMPTY);
  }

  // login chk
  var entity = new ItbUserModel({
    password  :password,
    mobile    :mobile,
    del_flg   :0,
  });
  entity.findFromDB(function(error, items){
    // process error
    if(error){
      console.log('users.js[login] find user error: '+error);
      return ret_func(0,CODE.CREATE_USER_ERROR);
    }

    if (items != null && items.length > 0) {
      // process success
      var retData={
        user_id:items[0].user_id,
        user_type:items[0].user_type,
        nickname:items[0].nickname||'',
        head_url:items[0].head_url||'',
        sign:items[0].signature||'',
        wxuid:items[0].wechat_token||'',
        wxunm:items[0].wechat_nickname||'',
        reg_uuid:items[0].uuid||'',
      };
      return ret_func(1,CODE.OPERATION_SUCCESS,retData);
    } else {
      // not found
      console.log('users.js[login] did not find user');
      return ret_func(0,CODE.LOGIN_CHECK_ERROR);
    }

  });

}
router.get('/login', login);
router.post('/login', login);

//------------------------------------------------------------------
/* 用微信账号登陆（首次登录时，默认注册一个用户）
 * 方式:POST
 * 参数 device: 0:PC, 1:iO, 2:android
 * 参数 wxuid: 微信uid
 * 参数 wxunm[可选]: 微信用户昵称
 * 参数 uuid: 设备标识符
 * */
function wxLogin(req, res, next) {
  // get parameter
  var device = req.body.device || req.query.device;// TODO
  //var password = req.body.password || req.query.password || '';
  var wxuid = req.body.wxuid || req.query.wxuid || '';
  var wxunm = req.body.wxunm || req.query.wxunm || '';
  var uuid = req.body.uuid || req.query.uuid || '';
  var DEF_PW = 'e10adc3949ba59abbe56e057f20f883e';// 默认密码: 123456

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data: data||{}
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  //if(typeof password=='undefined' || password == null || password.trim().length == 0){
  //  return ret_func(0,CODE.PASSWORD_EMPTY);
  //}
  if(typeof wxuid=='undefined' || wxuid == null || wxuid.trim().length == 0){
    return ret_func(0,"无效微信账号");
  }
  if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    return ret_func(0,"无效uuid");
  }

  // 检索微信账号
  var entity = new ItbUserModel({
    //password: password,
    wechat_token: wxuid,
    del_flg: 0,
  });
  entity.findFromDB(function(error, items){
    if(error){
      console.log('users.js [wxLogin] find user Err: '+error);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    // 找到则认为登录成功
    if (items != null && items.length > 0) {
      // process success
      var retData={
        user_id:items[0].user_id,
        user_type:items[0].user_type,
        nickname:items[0].nickname||'',
        head_url:items[0].head_url||'',
        sign:items[0].signature||'',
        wxuid:items[0].wechat_token||'',
        wxunm:items[0].wechat_nickname||'',
        reg_uuid:items[0].uuid||'',
      };
      return ret_func(1,CODE.OPERATION_SUCCESS,retData);

    } else {
      // 未找到则注册默认用户
      var newEnt = new ItbUserModel({
        user_name :'Wechat_User',
        user_type :1,
        wechat_token: wxuid,
        wechat_nickname: wxunm,
        password  :DEF_PW,
        uuid      :uuid,
      });
      newEnt.saveToDB(function(saveErr, userId){
        if(saveErr){
          console.log('users.js [wxLogin] create user Err:'+saveErr);
          return ret_func(0, CODE.CREATE_USER_ERROR);
        }

        var retData={
          user_id:userId,
          user_type:1,
          nickname:'',
          head_url:'',
          sign:'',
          wxuid:wxuid,
          wxunm:wxunm,
          reg_uuid:uuid,
        };
        return ret_func(1,CODE.OPERATION_SUCCESS,retData);
      });
    }
  });

}
router.get('/wxLogin', wxLogin);
router.post('/wxLogin', wxLogin);

//------------------------------------------------------------------
/* ［网站用］查询微信登录用户(存在mobile, 则登录成功,  不存在, 则验证手机号)
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 wxUnionId: 微信UnionId
 * 参数 uuid: 设备标识符
 * {
 *     "success":1,
 *     "msg":"成功",
 *     "data":{
 *         "head_url":"http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U1055/2016/10/283/155523134_gcb9j4mxfBidTJmlkYMI",
 *         "nickname":"呵呵哒",
 *         "reg_uuid":"B549E141-38A6-42C6-85FD-AFD68CC81A05",
 *         "sign":"",
 *         "user_id":1055,
 *         "user_type":1,
 *         "wxuid":"oi9hmuFowWtUDGHePAqOZyUP2fy4", // wechat_token
 *         "wxunm":"呵呵哒",// wechat_nickname
 *         "unionid":"oi9hmuFowWtUDGHePAqOZyUP2fy4",// wechat_token_union
 *         "mobile":"18872202619"
 *     }
 * }
 * 测试地址：http://localhost:3000/users/findMobileUserByWechatForWeb?device=0&wxUnionId=uuu&uuid=C37CE03F759EE23C9D6E2BD330D8151E-Android
 * */
function findMobileUserByWechatForWeb(req, res, next) {
  var device = req.body.device || req.query.device;
  var wxUnionId = req.body.wxUnionId || req.query.wxUnionId || '';
  var uuid = req.body.uuid || req.query.uuid || '';

  // check parameters
  if(typeof wxUnionId == 'undefined' || wxUnionId == null || wxUnionId.trim().length == 0) {
      return usersUtil.ret_func_json(0,"无效微信UnionID",{},res);
  }
  if(typeof uuid == 'undefined' || uuid == null || uuid.trim().length == 0){
      return usersUtil.ret_func_json(0, "无效uuid",{},res);
  }

  // 根据微信unionID查找用户
  usersUtil.get_mobileUserByWxUnionId(wxUnionId, function(error, user_item){
      if(error){
          console.log(error);
          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
      }
      // 找不到用户，则返回空对象
      if(user_item==null ){
          return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{},res);
      }else{
          // 找到用户，但是手机号为空，则返回空对象
          if(user_item.mobile==null ){
              return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{},res);// 没有数据时，或者没有手机号时，返回空对象
          }else{
              // 找到用户，且有手机号为空，且有openID活着unionID，则返回用户信息
              var retData = usersUtil.retDataWithITBUserModel(user_item);
              return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
          }
      }
  });

}
router.get('/findMobileUserByWechatForWeb', findMobileUserByWechatForWeb);
router.post('/findMobileUserByWechatForWeb', findMobileUserByWechatForWeb);
//------------------------------------------------------------------
/* 查询微信登录用户(存在mobile, 则登录成功,  不存在, 则验证手机号)
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 wxOpenId: 微信OpenId
 * 参数 wxUnionId: 微信UnionId
 * 参数 uuid: 设备标识符
 * {
 *     "success":1,
 *     "msg":"成功",
 *     "data":{
 *         "head_url":"http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U1055/2016/10/283/155523134_gcb9j4mxfBidTJmlkYMI",
 *         "nickname":"呵呵哒",
 *         "reg_uuid":"B549E141-38A6-42C6-85FD-AFD68CC81A05",
 *         "sign":"",
 *         "user_id":1055,
 *         "user_type":1,
 *         "wxuid":"oi9hmuFowWtUDGHePAqOZyUP2fy4", // wechat_token
 *         "wxunm":"呵呵哒",// wechat_nickname
 *         "unionid":"oi9hmuFowWtUDGHePAqOZyUP2fy4",// wechat_token_union
 *         "mobile":"18872202619"
 *     }
 * }
 * 测试地址：http://localhost:3000/users/findMobileUserByWechat?wxOpenId=oi9hmuL-Cl17B9eXVFN_W4VJIDGo&wxUnionId=o07tHvxUTrBN5JRpHwFr114g67zE&uuid=E2226826-646B-49DE-85A9-CD90904CD49C-iOS
 * */
function findMobileUserByWechat(req, res, next) {
  var device = req.body.device || req.query.device;
  var wxOpenId = req.body.wxOpenId || req.query.wxOpenId || '';
  var wxUnionId = req.body.wxUnionId || req.query.wxUnionId || '';
  var uuid = req.body.uuid || req.query.uuid || '';

  // check parameters
  if(typeof wxOpenId == 'undefined' || wxOpenId == null || wxOpenId.trim().length == 0){
    return usersUtil.ret_func_json(0,"无效微信OpenID",{},res);
  }
  if(typeof wxUnionId == 'undefined' || wxUnionId == null || wxUnionId.trim().length == 0) {
    return usersUtil.ret_func_json(0,"无效微信UnionID",{},res);
  }
  if(typeof uuid == 'undefined' || uuid == null || uuid.trim().length == 0){
    return usersUtil.ret_func_json(0, "无效uuid",{},res);
  }
  // 根据微信unionID或者openID查找用户
  usersUtil.get_mobileUserByWxUnionIdOrOpenId(wxUnionId, wxOpenId, function(error, user_item){
      if(error){
          console.log(error);
          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
      }
      // 找不到用户，则返回空对象
      if(user_item==null ){
          return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{},res);
      }else{
          // 找到用户，但是手机号为空，则返回空对象
          if(user_item.mobile==null ){
              return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{},res);// 没有数据时，或者没有手机号时，返回空对象
          }else{
              // 找到用户，且有手机号，但是openID或者unionID为空，则更新对象
              if(user_item.wechat_token ==null||user_item.wechat_token.length==0
                  || user_item.wechat_token_union ==null|| user_item.wechat_token_union.length ==0){
                  usersUtil.updateWxById(user_item.user_id, wxUnionId, wxOpenId, function(error){
                      if(error){
                          console.log(error);
                          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
                      }
                      // 返回用户信息
                      var retData = usersUtil.retDataWithITBUserModel(user_item);
                      retData.unionid = wxUnionId;
                      retData.wxuid = wxOpenId;
                      return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
                  });
              }else{
                  // 找到用户，且有手机号为空，且有openID活着unionID，则返回用户信息
                  var retData = usersUtil.retDataWithITBUserModel(user_item);
                  return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
              }
          }
      }
  });

}
router.get('/findMobileUserByWechat', findMobileUserByWechat);
router.post('/findMobileUserByWechat', findMobileUserByWechat);
//------------------------------------------------------------------
/* ［网站用］微信验证手机号登录：使用微信信息和手机号进行登录，具体逻辑见：svn://192.168.1.253:9999/design/dev/移动端文档/微信账号登录相关流程.png
 * 注意：此接口为了解决4.0以前的bug：微信登录只传递了OpenId，未传递UnionID。
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 wxUnionId: 微信UnionId
 * 参数 wxHeader： 微信头像地址
 * 参数 wxNickName： 微信 昵称
 * 参数 mobile：手机号
 * 参数 uuid: 设备标识符
 * {
 *     "success":1,
 *     "msg":"成功",
 *     "data":{
 *         "head_url":"http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U1055/2016/10/283/155523134_gcb9j4mxfBidTJmlkYMI",
 *         "nickname":"呵呵哒",
 *         "reg_uuid":"B549E141-38A6-42C6-85FD-AFD68CC81A05",
 *         "sign":"",
 *         "user_id":1055,
 *         "user_type":1,
 *         "wxuid":"oi9hmuFowWtUDGHePAqOZyUP2fy4", // wechat_token
 *         "wxunm":"呵呵哒",// wechat_nickname
 *         "unionid":"oi9hmuFowWtUDGHePAqOZyUP2fy4",// wechat_token_union
 *         "mobile":"18872202619"
 *     }
 * }
 * 测试地址：http://localhost:3000/users/loginByWechatAndMobileBeforeV4ForWeb?wxOpenId=oi9hmuL-Cl17B9eXVFN_W4VJIDGo&wxUnionId=o07tHvxUTrBN5JRpHwFr114g67zE&uuid=E2226826-646B-49DE-85A9-CD90904CD49C-iOS&wxHeader=http://wx.qlogo.cn/mmopen/RR3bx1SuyxrU3qo4hObUR8qopkwibvM70nCNFgD5QLIkcv3tLC4w1sTWGBXrjqiaLaicofRkr22tJUDp6smSMYZzPGd7oaBiaV3d/0&wxNickName=liumin&mobile=18696138681
 * */
function loginByWechatAndMobileBeforeV4ForWeb(req, res, next) {
  var device = req.body.device || req.query.device;
  var uuid = req.body.uuid || req.query.uuid || '';
  var wxUnionId = req.body.wxUnionId || req.query.wxUnionId || '';
  var wxHeader = req.body.wxHeader || req.query.wxHeader || '';
  var wxNickName = req.body.wxNickName || req.query.wxNickName || '';
  var mobile = req.body.mobile || req.query.mobile || '';

  // check parameters
  if (typeof wxUnionId == 'undefined' || wxUnionId == null || wxUnionId.trim().length == 0) {
    return usersUtil.ret_func_json(0, "无效微信UnionID", {}, res);
  }
  if (typeof wxHeader == 'undefined' || wxHeader == null || wxHeader.trim().length == 0) {
    return usersUtil.ret_func_json(0, "无效微信头像", {}, res);
  }
  if (typeof wxNickName == 'undefined' || wxNickName == null || wxNickName.trim().length == 0) {
    return usersUtil.ret_func_json(0, "无效微信昵称", {}, res);
  }
  if (typeof mobile == 'undefined' || mobile == null || mobile.trim().length == 0) {
    return usersUtil.ret_func_json(0, "无效微信手机", {}, res);
  }
  if (typeof uuid == 'undefined' || uuid == null || uuid.trim().length == 0) {
    return usersUtil.ret_func_json(0, "无效uuid", {}, res);
  }

  /*
   用户账户存在于5种情况：
   1、手机号                                  ［旧App、新App、网站］
   2、OpenID                                  ［旧App］
   3、手机号＋OpenID                           ［旧App］
   4、UnionID＋OpenID＋手机号                  ［新App］
   5、UnionID＋手机号                          ［新网站］
   * */

  // 手机号对应的用户纪录U存在？
  usersUtil.get_mobileUserByMobile(mobile, function(error, user_item){
    if(error){
      console.log(error);
      return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
    }
    if(user_item!=null){
      // 使用旧用户信息＋微信信息 进行登录的流程
      usersUtil.wxLoginWithExistMobileUserForWeb(wxUnionId,wxHeader,wxNickName,uuid,user_item, function(error, user_item){
        if(error) {
          console.log("users.js wxLoginWithExistMobileUserForWeb: " + error);
          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, null, res);
        }
        var retData = usersUtil.retDataWithITBUserModel(user_item);
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
      });

    }else{
      // 使用新手机号＋微信信息 进行登录的流程
      usersUtil.wxLoginWithoutExistMobileUserForWeb(wxUnionId,wxHeader,wxNickName,uuid,mobile,function(error, user_item){
        if(error) {
          console.log("users.js  wxLoginWithoutExistMobileUserForWeb: " + error);
          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, null, res);
        }
        var retData = usersUtil.retDataWithITBUserModel(user_item);
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
      });
    }
  });


}
router.get('/loginByWechatAndMobileBeforeV4ForWeb', loginByWechatAndMobileBeforeV4ForWeb);
router.post('/loginByWechatAndMobileBeforeV4ForWeb', loginByWechatAndMobileBeforeV4ForWeb);
//------------------------------------------------------------------
/* 微信验证手机号登录：使用微信信息和手机号进行登录，具体逻辑见：svn://192.168.1.253:9999/design/dev/移动端文档/微信账号登录相关流程.png
 * 注意：此接口为了解决4.0以前的bug：微信登录只传递了OpenId，未传递UnionID。
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 wxOpenId: 微信OpenId
 * 参数 wxUnionId: 微信UnionId
 * 参数 wxHeader： 微信头像地址
 * 参数 wxNickName： 微信 昵称
 * 参数 mobile：手机号
 * 参数 uuid: 设备标识符
 * {
 *     "success":1,
 *     "msg":"成功",
 *     "data":{
 *         "head_url":"http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U1055/2016/10/283/155523134_gcb9j4mxfBidTJmlkYMI",
 *         "nickname":"呵呵哒",
 *         "reg_uuid":"B549E141-38A6-42C6-85FD-AFD68CC81A05",
 *         "sign":"",
 *         "user_id":1055,
 *         "user_type":1,
 *         "wxuid":"oi9hmuFowWtUDGHePAqOZyUP2fy4", // wechat_token
 *         "wxunm":"呵呵哒",// wechat_nickname
 *         "unionid":"oi9hmuFowWtUDGHePAqOZyUP2fy4",// wechat_token_union
 *         "mobile":"18872202619"
 *     }
 * }
 * 测试地址：http://localhost:3000/users/loginByWechatAndMobileBeforeV4?wxOpenId=oi9hmuL-Cl17B9eXVFN_W4VJIDGo&wxUnionId=o07tHvxUTrBN5JRpHwFr114g67zE&uuid=E2226826-646B-49DE-85A9-CD90904CD49C-iOS&wxHeader=http://wx.qlogo.cn/mmopen/RR3bx1SuyxrU3qo4hObUR8qopkwibvM70nCNFgD5QLIkcv3tLC4w1sTWGBXrjqiaLaicofRkr22tJUDp6smSMYZzPGd7oaBiaV3d/0&wxNickName=liumin&mobile=13554344638
 * */
function loginByWechatAndMobileBeforeV4(req, res, next) {
  var device = req.body.device || req.query.device;
  var uuid = req.body.uuid || req.query.uuid || '';
  var wxOpenId = req.body.wxOpenId || req.query.wxOpenId || '';
  var wxUnionId = req.body.wxUnionId || req.query.wxUnionId || '';
  var wxHeader = req.body.wxHeader || req.query.wxHeader || '';
  var wxNickName = req.body.wxNickName || req.query.wxNickName || '';
  var mobile = req.body.mobile || req.query.mobile || '';

  // check parameters
  if(typeof wxOpenId == 'undefined' || wxOpenId == null || wxOpenId.trim().length == 0){
    return usersUtil.ret_func_json(0,"无效微信OpenID",{},res);
  }
  if(typeof wxUnionId == 'undefined' || wxUnionId == null || wxUnionId.trim().length == 0) {
    return usersUtil.ret_func_json(0,"无效微信UnionID",{},res);
  }
  if(typeof wxHeader == 'undefined' || wxHeader == null || wxHeader.trim().length == 0) {
    return usersUtil.ret_func_json(0,"无效微信头像",{},res);
  }
  if(typeof wxNickName == 'undefined' || wxNickName == null || wxNickName.trim().length == 0) {
    return usersUtil.ret_func_json(0,"无效微信昵称",{},res);
  }
  if(typeof mobile == 'undefined' || mobile == null || mobile.trim().length == 0) {
    return usersUtil.ret_func_json(0,"无效微信手机",{},res);
  }
  if(typeof uuid == 'undefined' || uuid == null || uuid.trim().length == 0){
    return usersUtil.ret_func_json(0, "无效uuid",{},res);
  }

  /*
   用户账户存在于5种情况：
   1、手机号                                  ［旧App、新App、网站］
   2、OpenID                                  ［旧App］
   3、手机号＋OpenID                           ［旧App］
   4、UnionID＋OpenID＋手机号                  ［新App］
   5、UnionID＋手机号                          ［新网站］
  * */
  // 手机号对应的用户纪录U存在？
  usersUtil.get_mobileUserByMobile(mobile, function(error, user_item){
      if(error){
          console.log(error);
          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
      }
      if(user_item!=null){
          // 使用旧用户信息＋微信信息 进行登录的流程
          usersUtil.wxLoginWithExistMobileUser(wxUnionId,wxOpenId,wxHeader,wxNickName,uuid,user_item, function(error, user_item){
              if(error) {
                  console.log("users.js wxLoginWithExistMobileUser: " + error);
                  return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, null, res);
              }
              var retData = usersUtil.retDataWithITBUserModel(user_item);
              return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
          });

      }else{
          // 使用新手机号＋微信信息 进行登录的流程
          usersUtil.wxLoginWithoutExistMobileUser(wxUnionId,wxOpenId,wxHeader,wxNickName,uuid,mobile,function(error, user_item){
              if(error) {
                  console.log("users.js  wxLoginWithoutExistMobileUser: " + error);
                  return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, null, res);
              }
              var retData = usersUtil.retDataWithITBUserModel(user_item);
              return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
          });
      }
  });
}
router.get('/loginByWechatAndMobileBeforeV4', loginByWechatAndMobileBeforeV4);
router.post('/loginByWechatAndMobileBeforeV4', loginByWechatAndMobileBeforeV4);
//------------------------------------------------------------------
/* [废弃]用微信账号登陆（首次登录时，默认注册一个用户）
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 wxuid: 微信uid
 * 参数 uuid: 设备标识符
 * 参数 wxunm[可选]: 微信用户昵称
 * 参数 unionid: 唯一标识
 * */
function wechatLogin(req, res, next){
  // get parameters
  var device = req.body.device || req.query.device;
  var wxuid = req.body.wxuid || req.query.wxuid || '';
  var wxunm = req.body.wxunm || req.query.wxunm || '';
  var uuid = req.body.uuid || req.query.uuid || '';
  var DEF_PW = 'e10adc3949ba59abbe56e057f20f883e';
  var unionid = req.body.unionid || req.query.unionid || null; // 数据库对应: wechat_token_union

  // check parameters
  if(typeof wxuid == 'undefined' || wxuid == null || wxuid.trim().length == 0){
    return ret_func(0,"无效微信账号");
  }
  if(typeof uuid == 'undefined' || uuid == null || uuid.trim().length == 0) {
    return ret_func(0,"无效uuid");
  }
  if(typeof unionid == 'undefined' || unionid == null || unionid.trim().length == 0){
    return ret_func(0, "无效unionid");
  }

  var userInfo = new ItbUserModel({
    user_name :'Wechat_User',
    user_type :1,
    wechat_token: wxuid,
    wechat_nickname: wxunm,
    password  :DEF_PW,
    uuid      :uuid,
    wechat_token_union : unionid
  });

  // 判断类型, 是 web 登录还是 app 登录
  // web 登录的情况
  if (device == 0) {
      usersUtil.webWechatLogin(userInfo, function(webWechatLoginErr, loginUser){
        if(webWechatLoginErr) {
          console.log("users.js [wechatLogin] webWechatLoginErr: " + webWechatLoginErr);
          usersUtil.ret_func_json(1, CODE.OPERATION_FAILED, null, res);
        }
        var retData = usersUtil.retDataWithITBUserModel(loginUser);
        usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
      });
  }
  // 移动端app 微信登录
  else {
    usersUtil.appWechatLogin(userInfo, function(appWechatLoginErr, loginUser){
      if(appWechatLoginErr) {
        console.log("users.js [wechatLogin] appWechatLoginErr: " + appWechatLoginErr);
        usersUtil.ret_func_json(1, CODE.OPERATION_FAILED, null, res);
      }
      var retData = usersUtil.retDataWithITBUserModel(loginUser);
      usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
    });
  }
}
router.get('/wechatLogin', wechatLogin);
router.post('/wechatLogin', wechatLogin);

//------------------------------------------------------------------

//------------------------------------------------------------------
/* 重设密码.
 * 方式:POST
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:mobile:手机号
 * 参数:password:MD5加密的密码
 * 参数:oldPassword:旧密码 *不需要
 * */
function resetPassword(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var password = req.body.password || req.query.password;
  //var oldPassword = req.body.oldPassword || req.query.oldPassword;
  var mobile = req.body.mobile || req.query.mobile;

  // return function
  function ret_func(success, msg){
    var obj = {
      success:success,
      msg:msg,
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof password=='undefined' ){
    return ret_func(0,CODE.PASSWORD_EMPTY);
  }
  //if(typeof oldPassword=='undefined'){
  //  return ret_func(0,CODE.PASSWORD_EMPTY);
  //}
  if(typeof mobile=='undefined'){
    return ret_func(0,CODE.MOBILE_EMPTY);
  }

  // check user
  var entity = new ItbUserModel({
    mobile: mobile,
    del_flg: 0
  });
  entity.findCountFromDB(function(err, cnt){
    if(err){
      console.log('users.js [resetPassword] find User Err: '+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    if(cnt>0){
      var entity = new ItbUserModel({
        //oldPassword:oldPassword,
        password  :password,
        mobile    :mobile,
      });
      entity.updatePasssword(function(error){
        // process error
        if(error){
          console.log('users.js[resetPassword] update password error: '+error);
          return ret_func(0,CODE.UPDATE_PASSWORD_ERROR);
        }

        return ret_func(1,CODE.OPERATION_SUCCESS);
      });
    }else{
      return ret_func(0,"未注册用户");
    }
  });

}
router.get('/resetPassword', resetPassword);
router.post('/resetPassword', resetPassword);


//------------------------------------------------------------------
/* 收藏.
 * 方式:GET
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:user_id:用户id
 * 参数:base_doc_id:文档id
 * */
function collect(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var user_id = req.body.user_id || req.query.user_id;
  var doc_id = req.body.base_doc_id || req.query.base_doc_id;

  // return function
  function ret_func(success, msg, collect_id){
    var obj = {
      success:success,
      msg:msg,
      data: {
        collect_id:collect_id
      }
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof user_id=='undefined' || user_id == null || user_id.trim().length == 0){
    return ret_func(0,CODE.USER_ID_EMPTY);
  }
  if(typeof doc_id=='undefined' || doc_id == null || doc_id.trim().length == 0){
    return ret_func(0,CODE.DOC_ID_EMPTY);
  }

  // INSERT
  var entity = new ItbCollectModel({
    user_id   :user_id,
    doc_id    :doc_id,
    update_by :user_id,
    del_flg   :0
  });
  // 先检索
  entity.findFromDB(function(error, items){
    if(error){
      console.log('user.js collect error:'+error);
      return ret_func(0,CODE.CREATE_COLLECT_ERROR);
    }

    if (items == null || items.length == 0) {
      // 未检索到时新规
      entity.saveToDB(function(error, id){
        // process error
        if(error){
          console.log('user.js collect error:'+error);
          return ret_func(0,CODE.CREATE_COLLECT_ERROR);
        }
        // process success
        return ret_func(1,CODE.OPERATION_SUCCESS,id);
      });

    } else {
      // 检索到时直接返回
      return ret_func(1,CODE.OPERATION_SUCCESS,items[0].collect_id);
    }
  });

}
router.get('/collect', collect);
router.post('/collect', collect);

//------------------------------------------------------------------
/* 取消收藏.
 * 方式:GET
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:user_id:用户id
 * 参数:base_doc_id:文档id
 * */
function removeCollect(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var user_id = req.body.user_id || req.query.user_id;
  var doc_id = req.body.base_doc_id || req.query.base_doc_id;

  // return function
  function ret_func(success, msg){
    var obj = {
      success:success,
      msg:msg,
      data: {
      }
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof user_id=='undefined' || user_id == null || user_id.trim().length == 0){
    return ret_func(0,CODE.USER_ID_EMPTY);
  }
  if(typeof doc_id=='undefined' || doc_id == null || doc_id.trim().length == 0){
    return ret_func(0,CODE.DOC_ID_EMPTY);
  }

  var entity = new ItbCollectModel({
    user_id   :user_id,
    doc_id    :doc_id,
    update_by :user_id,
  });
  entity.deleteCollectLogic(function(error){
    // process error
    if(error){
      console.log('users.js[removeCollect] delete collect error: '+error);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    return ret_func(1,CODE.OPERATION_SUCCESS);
  });
}
router.get('/removeCollect', removeCollect);
router.post('/removeCollect', removeCollect);

/* 收藏列表.
 * 方式:GET
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:user_id:用户id
 * 参数:pageNum:页码,从0开始
 * 参数:pageSize:每页容量
 * */
function collectList(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var user_id = req.body.user_id || req.query.user_id;
  var pageNum = req.body.pageNum || req.query.pageNum;
  var pageSize = req.body.pageSize || req.query.pageSize;

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success: success,
      msg: msg,
      data: data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof user_id=='undefined' || user_id == null || user_id.trim().length == 0){
    return ret_func(0,CODE.USER_ID_EMPTY);
  }
  if(typeof pageNum=='undefined' || pageNum == null || pageNum.trim().length == 0){
    return ret_func(0,CODE.PAGENUM_EMPTY);
  }
  if(typeof pageSize=='undefined' || pageSize == null || pageSize.trim().length == 0){
    return ret_func(0,CODE.PAGESIZE_EMPTY);
  }

  // 分页: 跳过条数
  var skipCnt = Number(pageNum) * Number(pageSize);

  var entity = new ItbCollectModel({
    user_id: user_id,
    del_flg: 0
  });
  // 分页查询
  entity.getCollectInfoList(function(err, items){
    if (err){
      console.log('users.js[collectList] collect find error: '+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    var collectData = [];
    for (var i in items) {
      var item = items[i];
      var itemData = {
        "base_doc_id": item.doc_id,
        "image": item.thumb_s,
        "title": item.doc_name,
        "style": item.grp_type_name, // 分类(路演, 发布会等)
        "createDate": item.create_time,
        "pageCount": item.page_count
      }
      collectData.push(itemData);
    }
    return ret_func(1,CODE.OPERATION_SUCCESS,collectData);
  },skipCnt,pageSize);

  //var obj = {
  //  success:1,msg:'success',
  //  "data": [
  //    {
  //      "base_doc_id": 1,
  //      "image": BASE_IP + '/images/1.jpg',
  //      "title": "乐工作 悦生活 自我充电课程",
  //      "style": "发布会",                      // 分类(路演, 发布会等)
  //      "createDate": "2015-03-31 10:51",
  //      "pageCount":23
  //    },
  //    {
  //      "base_doc_id": 2,
  //      "image": BASE_IP + '/images/2.jpg',
  //      "title": "Project analysis",
  //      "style": "路演",                      // 分类
  //      "createDate": "2015-03-31 10:51",
  //      "pageCount":23
  //    }
  //  ]
  //};

}
router.get('/collectList', collectList);
router.post('/collectList', collectList);

//------------------------------------------------------------------
/* 意见反馈.
 * 方式:POST
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:likeDesign:0喜欢／1还行／2不喜欢
 * 参数:likeProduct:0喜欢／1还行／2不喜欢
 * 参数:advice:意见内容
 * 参数:mail:邮箱地址
 * 参数:user_id
 * */
function feedback(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var likeDesign = req.body.likeDesign || req.query.likeDesign;
  var likeProduct = req.body.likeProduct || req.query.likeProduct;
  var advice = req.body.advice || req.query.advice;
  var mail = req.body.mail || req.query.mail;
  var user_id = req.body.user_id || req.query.user_id;

  // return function
  function ret_func(success, msg, id){
    var obj = {
      success:success,
      msg:msg,
      data:{id: id}
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  //if(typeof likeDesign=='undefined' || likeDesign == null || likeDesign.trim().length == 0){
  //  return ret_func(0,CODE.FEEDBACK_EMPTY);
  //}
  //if(typeof likeProduct=='undefined' || likeProduct == null || likeProduct.trim().length == 0){
  //  return ret_func(0,CODE.FEEDBACK_EMPTY);
  //}
  // 邮箱改为可选项
  //if(typeof mail=='undefined' || mail == null || mail.trim().length == 0){
  //  return ret_func(0,CODE.MAIL_EMPTY);
  //}

  var entity = new ItbFeedbackModel({
    like_design: likeDesign,
    like_product: likeProduct,
    advice: advice,
    mail: mail,
    user_id: user_id
  });

  entity.saveToDB(function(error, id){
    // process error
    if(error){
      console.log('users.js[feedback] insert error: '+error);
      return ret_func(0,CODE.OPERATION_FAILED);
    }
    // process success
    return ret_func(1,CODE.OPERATION_SUCCESS,id);
  });

}
router.get('/feedback', feedback);
router.post('/feedback', feedback);

//------------------------------------------------------------------

//------------------------------------------------------------------
/* 删除用户作品.
 * 方式:GET
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:base_doc_id:文档id
 * 参数:user_id:用户id(如果不为空，用user_id查找用户，如果为空，用uuid查找用户)
 * 参数:uuid
 *
 * 注意：用base_doc_id 作为 doc_id 到 itb_document 中查找
 *      如果是模版，则直接返回
 *      如果是用户作品，则删除db中该作品，并返回
 * */
function removeUserDesign(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var doc_id = req.body.base_doc_id || req.query.base_doc_id;
  var uuid = req.body.uuid || req.query.uuid;
  var user_id = req.body.user_id || req.query.user_id || '';

  // return function
  function ret_func(success, msg){
    var obj = {
      success:success,
      msg:msg,
      data:{}
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof doc_id=='undefined' || doc_id == null || doc_id.trim().length == 0){
    return ret_func(0,CODE.DOC_ID_EMPTY);
  }
  // user_id和uuid必须有一个存在
  var is_user_id_empty = false;
  var is_uuid_empty = false;
  if(typeof user_id=='undefined' || user_id == null || user_id.trim().length == 0) {
    is_user_id_empty = true;
  }
  if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    is_uuid_empty = true;
  }
  if(is_user_id_empty && is_uuid_empty){
    return ret_func(0,CODE.USER_ID_EMPTY+CODE.UUID_EMPTY);
  }


  // 用user_id/uuid检索user信息
  var chkEntity = null;
  if (user_id != null && user_id.trim().length>0){
    // user_id检索
    chkEntity = new ItbUserModel({
      user_id:user_id,
      del_flg:0
    });
  } else {
    // uuid检索
    chkEntity = new ItbUserModel({
      uuid:uuid,
      del_flg:0
    });
  }
  chkEntity.findFromDB(function(err, users){
    if(err){
      console.log('users.js[removeUserDesign] find user err:'+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    // 用户存在时
    if (users != null && users.length > 0){
      var user = users[0];

      var entity = new ItbDocumentModel({
        doc_id: doc_id,
        del_flg: 0
      });
      // 检索文档
      entity.findFromDB(function(error, items){
        // process error
        if(error){
          console.log('users.js[removeUserDesign] find doc err:'+error);
          return ret_func(0,CODE.OPERATION_FAILED);
        }

        // 文档存在时
        if (items != null && items.length > 0) {
          if (items[0].user_id != user.user_id) {
            console.log('users.js[removeUserDesign] delete doc not allowed');
            return ret_func(0,CODE.DELETE_DOC_NOT_ALLOWED);
          }

          var base_doc_id = items[0].base_doc_id;
          if (base_doc_id == null || base_doc_id.length == 0 || base_doc_id == items[0].doc_id) {
            // 公共模版
            console.log('users.js[removeUserDesign] delete TEMPLATE not allowed');
            return ret_func(0,CODE.DELETE_TEMPLATE_ERROR);
          } else {
            // 用户文档
            var updateBy = user.user_name || user.user_id;
            var entity2 = new ItbDocumentModel({
              doc_id: doc_id,
              update_by: updateBy
            });
            entity2.deleteDocAndPagesLogic(function(err){
              if (err) {
                console.log('users.js[removeUserDesign] delete error: ' + err);
                return ret_func(0,CODE.DELETE_TEMPLATE_ERROR);
              } else {
                return ret_func(1,CODE.OPERATION_SUCCESS);
              }
            });
          }
        } else {
          console.log('users.js[removeUserDesign] doc not found');
          return ret_func(1,CODE.OPERATION_SUCCESS);
        }
      });
    } else {
      // 用户不存在时
      console.log('users.js[removeUserDesign] user not found');
      return ret_func(0,CODE.UNKNOWN_USER);
    }
  });

}
router.get('/removeUserDesign', removeUserDesign);
router.post('/removeUserDesign', removeUserDesign);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 删除指定用户的全部作品.
 * 方式:GET
 * 参数:device:0表示从pc,1表示iOS,2表示android
 * 参数:user_id:用户id
 * 参数:uuid
 *
 * 注意：如果是模版，则直接返回
 *      如果是用户作品，则删除db中该作品，并返回
 * */
function removeAllUserDesign(req, res, next) {
  // get parameter
  var pc = req.body.pc || req.query.pc;// TODO
  var uuid = req.body.uuid || req.query.uuid;
  var user_id = req.body.user_id || req.query.user_id;

  // return function
  function ret_func(success, msg){
    var obj = {
      success:success,
      msg:msg,
      data:{}
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof user_id=='undefined' || user_id == null || user_id.trim().length == 0){
    return ret_func(0,CODE.USER_ID_EMPTY);
  }
  if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    return ret_func(0,CODE.UUID_EMPTY);
  }

  // 检索user信息
  var chkEntity = new ItbUserModel({
    user_id:user_id,
    //uuid:uuid,
    del_flg:0
  });
  chkEntity.findFromDB(function(err, users){
    if(err){
      console.log('users.js[removeAllUserDesign] find user err:'+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    // 用户存在时
    if (users != null && users.length > 0){
      var user = users[0];

      // 查找文档
      var entity = new ItbDocumentModel({
        user_id:user_id,
        //uuid:uuid,
        user_type:1,
        del_flg:0,
      });
      entity.findFromDB(function(error, items){
        // process error
        if(error){
          console.log('users.js[removeAllUserDesign] find doc err:'+error);
          return ret_func(0,CODE.OPERATION_FAILED);
        }

        if(items != null && items.length>0){
          // 同步更新
          var asyncFuncs = [];
          for (var i in items) {
            asyncFuncs.push((function (index, docInfo) {
              return function (asyncCallback) {
                var updEntity = new ItbDocumentModel({
                  doc_id: docInfo.doc_id,
                  update_by: user_id,
                });
                updEntity.deleteDocAndPagesLogic(function(err){
                  asyncCallback(err);
                });
              }// ret func
            })(i, items[i])); // 利用闭包解决动态参数传递问题
          }
          async.parallel(asyncFuncs, function (err) {
            if (err) {
              console.log('users.js[removeAllUserDesign] update error: '+err);
              return ret_func(0,CODE.OPERATION_FAILED);
            }

            return ret_func(1,CODE.OPERATION_SUCCESS);
          });
        }
      });

    } else {
      // 用户不存在时
      console.log('users.js[removeAllUserDesign] user not found');
      return ret_func(0,CODE.UNKNOWN_USER);
    }
  });

}
router.get('/removeAllUserDesign', removeAllUserDesign);
router.post('/removeAllUserDesign', removeAllUserDesign);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取临时用户ID: 如果存在对应uuid的临时用户,则返回该用户id,否则新建临时用户
 * 方式:GET
 * 参数 device: 0:PC, 1:iO, 2:android
 * 参数 uuid: 设备标识符
 *
 * 返回: {
 *         "success": 1,
 *         "msg": "成功",
 *         "data": {temp_id: 18}
 *      }
 * */
function getTempUserId(req, res, next) {
  // get parameter
  var device = req.body.device || req.query.device;// TODO
  var uuid = req.body.uuid || req.query.uuid;

  // return function
  function ret_func(success,msg, id){
    var obj = {
      success:success,
      msg:msg,
      data: {
        temp_id:id,
      }
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  return ret_func(0, '失败', null);

  // // check parameter
  // if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
  //   return ret_func(0, CODE.UUID_EMPTY);
  // }
  //
  // // 创建临时user
  // var chkEntity = new ItbUserModel({
  //   uuid: uuid
  // });
  // chkEntity.getTempUserByUUID(function(error,items){
  //   if(error){
  //     console.log('[users.js] getTempUserId find error:'+error);
  //     return ret_func(0, CODE.CREATE_USER_ERROR);
  //   }
  //
  //   if(items!=null && items.length>0){
  //     // 返回已有临时用户id
  //     console.log('[users.js] getTempUserId OldID:'+items[0].user_id);
  //     return ret_func(1, CODE.OPERATION_SUCCESS, items[0].user_id);
  //
  //   }else{
  //     // 新建临时用户
  //     var entity = new ItbUserModel({
  //       password  : 'e10adc3949ba59abbe56e057f20f883e',// 123456
  //       uuid      : uuid,
  //       user_type : 1,
  //     });
  //     entity.saveToDB(function(err, newUserId){
  //       if(err){
  //         console.log('[users.js] getTempUserId insert error:'+err);
  //         return ret_func(0, CODE.CREATE_USER_ERROR);
  //       }
  //       // process success
  //       console.log('[users.js] getTempUserId NewID:'+newUserId);
  //       return ret_func(1, CODE.OPERATION_SUCCESS, newUserId);
  //     });
  //   }
  // });

}
router.get('/getTempUserId', getTempUserId);
router.post('/getTempUserId', getTempUserId);

//------------------------------------------------------------------
/* 用户注册: 先检查mobile是否被注册过，后检查tempId是否存在
 *
 * 方式:GET
 * 参数 device: 0:PC, 1:iO, 2:android
 * 参数 uuid: 设备标识符
 * 参数 tempId: 临时用户id（存在时续用此id作为用户id, 不存在时新建用户id）
 * 参数 mobile: 手机号
 * 参数 password: MD5加密的密码
 *
 * 返回: {
 *         "success": 1,
 *         "msg": "成功",
 *         "data": {user_id: 18}
 *      }
 * */
function userRegist(req, res, next) {
  // get parameter
  var device = req.body.device || req.query.device;// TODO
  var uuid = req.body.uuid || req.query.uuid;
  var tempId = req.body.tempId || req.query.tempId || "";
  var DEF_PW = 'e10adc3949ba59abbe56e057f20f883e';// 默认密码: 123456
  var password = req.body.password || req.query.password;
  var mobile = req.body.mobile || req.query.mobile;

  // return function
  function ret_func(success,msg, id){
    var obj = {
      success:success,
      msg:msg,
      data: {
        user_id:id,
      }
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if(typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    return ret_func(0, CODE.UUID_EMPTY);
  }
  if(typeof mobile=='undefined' || mobile == null || mobile.trim().length == 0){
    return ret_func(0, CODE.MOBILE_EMPTY);
  }
  if(typeof password=='undefined' || password == null || password.trim().length == 0){
    return ret_func(0, CODE.PASSWORD_EMPTY);
  }

  // check Mobile
  var chkEntity = new ItbUserModel({
    mobile: mobile,
    del_flg: 0
  });
  chkEntity.findFromDB(function(err, items) {
    if (err) {
      console.log('[users.js] [userRegist] check mobile error:' + err);
      return ret_func(0, CODE.CREATE_USER_ERROR);
    }

    if (items != null && items.length > 0) {
      // 该手机号已注册过
      var userId = items[0].user_id;
      console.log('[users.js] [userRegist] user exist! userId:'+userId);
      return ret_func(0, CODE.CREATE_USER_EXIST,userId);

    } else {
      // 该手机号未注册过
      // Check temp－UserId
      var chkEntity2 = new ItbUserModel({
        user_id: tempId,
        del_flg: 0
      });
      chkEntity2.findFromDB(function(err, items){
        if(err){
          console.log('[users.js] [userRegist] check error:'+err);
          return ret_func(0,CODE.CREATE_USER_ERROR);
        }

        if (items != null && items.length > 0) {
          // 已注册过
          var updEntity = new ItbUserModel({
            user_id   :tempId,
            user_name :mobile,
            user_type :1,
            password  :password,
            mobile    :mobile,
            uuid      :uuid,
          });
          updEntity.updateInfoById(function(error, results){
            if(error){
              console.log('[users.js] [userRegist] update user error:'+error);
              return ret_func(0, CODE.CREATE_USER_ERROR);
            }
            // process success
            return ret_func(1, CODE.OPERATION_SUCCESS, tempId);
          });

        } else {
          // 新建用户
          var entity = new ItbUserModel({
            user_name :mobile,
            user_type :1,
            password  :password,
            mobile    :mobile,
            uuid      :uuid,
          });
          entity.saveToDB(function(error, userId){
                // process error
                if(error){
                  console.log('[users.js] [userRegist] create user error:'+error);
                  return ret_func(0, CODE.CREATE_USER_ERROR);
                }

                // 兑换优惠券并尝试添加为下线 //todo
                usersUtil.exchgCouponAndTryAddPartnerCustom(mobile, function () {
                    // process success
                    console.log('[users.js] [userRegist] create user ID:'+userId);
                    return ret_func(1, CODE.OPERATION_SUCCESS, userId);
                });

          });
        }
      });
    }
  });

}
router.get('/userRegist', userRegist);
router.post('/userRegist', userRegist);

//------------------------------------------------------------------
/* 更新用户信息（昵称／头像／签名／微信用户昵称）
 * 方式:POST
 * 参数: device:
 * 参数: uuid: 设备唯一标识(注册时的uuid)
 * 参数: userId: 用户id
 * 参数: info: json字符串(未设置的项目不更新)
 * {
 *    "nickName": xxx,
 *    "headUrl": yyy,
 *    "sign": zzz,
 *    "wxName": name
 * }
 * */
function updUserInfo(req, res, next) {
  // get parameter
  var device = req.body.device || req.query.device;// TODO
  var uuid = req.body.uuid || req.query.uuid || '';
  var userId = Number(req.body.userId || req.query.userId || '0');
  var infoStr = req.body.info || req.query.info || '{}';
  var updInfo = JSON.parse(infoStr);

  // return function
  function ret_func(success, msg){
    var obj = {
      success:success,
      msg:msg,
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
    return ret_func(0,"无效用户id");
  }
  if (typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    return ret_func(0, CODE.UUID_EMPTY);
  }


  if( updInfo.length==0
      || (!updInfo.hasOwnProperty("nickName")
          && !updInfo.hasOwnProperty("headUrl")
          && !updInfo.hasOwnProperty("sign")
          && !updInfo.hasOwnProperty("wxName")) ) {
    // 无需更新
    return ret_func(0,"参数错误");
  }

  // check user
  var entity = new ItbUserModel({
    user_id: userId,
    uuid: uuid,
    del_flg: 0
  });
  entity.findCountFromDB(function(err, cnt){
    if(err){
      console.log('users.js [updUserInfo] find User Err: '+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    if(cnt>0){
      // do update
      var param = {user_id: userId};
      if(updInfo.hasOwnProperty("nickName")){
        param.nickname = updInfo.nickName || '';
      }
      if(updInfo.hasOwnProperty("headUrl")){
        param.head_url = updInfo.headUrl || '';
      }
      if(updInfo.hasOwnProperty("sign")){
        param.signature = updInfo.sign || '';
      }
      if(updInfo.hasOwnProperty("wxName")){
        param.wechat_nickname = updInfo.wxName || '';
      }
      var updEnt = new ItbUserModel(param);
      updEnt.updateToDB(function(error){
        // process error
        if(error){
          console.log('users.js [updUserInfo] Upd Err: '+error);
          return ret_func(0,CODE.OPERATION_FAILED);
        }

        return ret_func(1,CODE.OPERATION_SUCCESS);
      });

    } else {
      return ret_func(0,"非法用户");
    }

  });
}
router.get('/updUserInfo', updUserInfo);
router.post('/updUserInfo', updUserInfo);

//------------------------------------------------------------------
/* 绑定微信到已注册手机用户
 * 方式:POST
 * 参数: device:
 * 参数: uuid: 设备唯一标识(注册时的uuid)
 * 参数: userId: 用户id
 * 参数: wxuid: 微信uid
 * 参数: wxunm: 微信用户昵称
 * */
function bindWechat(req, res, next) {
  // get parameter
  var device = req.body.device || req.query.device;// TODO
  var uuid = req.body.uuid || req.query.uuid || '';
  var userId = Number(req.body.userId || req.query.userId || '0');
  var wxuid = req.body.wxuid || req.query.wxuid || '';
  var wxunm = req.body.wxunm || req.query.wxunm || '';

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
    return ret_func(0,"无效用户id");
  }
  if (typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    return ret_func(0, CODE.UUID_EMPTY);
  }
  if (typeof wxuid=='undefined' || wxuid == null || wxuid.trim().length == 0){
    return ret_func(0, "无效微信用户id");
  }

  // 检查用户
  var chkEnt = new ItbUserModel({
    user_id: userId,
    uuid: uuid,
    del_flg: 0
  });
  chkEnt.findCountFromDB(function(err, cnt){
    if(err){
      console.log('users.js [bindWechat] check User Err: '+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    if(cnt>0){
      // 检查微信号是否注册过
      var entity = new ItbUserModel({
        wechat_token: wxuid,
        del_flg: 0,
      });
      entity.findFromDB(function(err2, items){
        if(err2){
          console.log('users.js [bindWechat] find Wechat Err: '+err2);
          return ret_func(0,CODE.OPERATION_FAILED);
        }

        if(items && items.length>0){
          // 微信号注册过
          if(items.length>1){
            return ret_func(0,"该微信账号已被注册多次");
          }

          var wxUser=items[0];
          if(wxUser.user_id == userId){
            return ret_func(0,"该微信账号已经绑定当前用户");
          }

          if(wxUser.mobile && (wxUser.mobile+'').length>1){
            return ret_func(0,"该微信账号已经绑定其它用户");
          }

          // 将微信账户转移到目标用户
          var bindEnt = new ItbUserModel({
            user_id: userId,
            wechat_token: wxuid,
            wechat_nickname: wxunm
          });
          bindEnt.updateToDB(function(error){
            // process error
            if(error){
              console.log('users.js [bindWechat] Upd Err: '+error);
              return ret_func(0,CODE.OPERATION_FAILED);
            }

            // 删除原微信注册账户
            var delEnt = new ItbUserModel({
              user_id: wxUser.user_id,
              del_flg: 1,
            });
            delEnt.updateToDB(function(error2){
              if(error2){
                console.log('users.js [bindWechat] Del Err: '+error2);
                return ret_func(0,CODE.OPERATION_FAILED);
              }

              // 转移用户ppt文档
              var docEnt = new ItbDocumentModel({
                user_id_from : wxUser.user_id,
                user_id_to : userId
              });
              docEnt.moveDocByUser(function(err3,ret){
                if (err3) {
                  console.log('users.js [bindWechat] move Doc Err: ' + err3);
                  return ret_func(0,CODE.OPERATION_FAILED);
                }

                // 转移用户竖屏文档
                var tgEnt = new TgUserDocModel({
                  user_id_from : wxUser.user_id,
                  user_id_to : userId
                });
                tgEnt.moveDocByUser(function(err4,ret2){
                  if (err4) {
                    console.log('users.js [bindWechat] move TgDoc Err: ' + err4);
                    return ret_func(0,CODE.OPERATION_FAILED);
                  }
                  
                  return ret_func(1,CODE.OPERATION_SUCCESS);
                });// upd
              });// upd

            });// del

          });// bind

        } else {
          // 微信号未注册过,绑定到当前用户
          var bindEnt = new ItbUserModel({
            user_id: userId,
            wechat_token: wxuid,
            wechat_nickname: wxunm
          });
          bindEnt.updateToDB(function(error){
            // process error
            if(error){
              console.log('users.js [bindWechat] Upd Err: '+error);
              return ret_func(0,CODE.OPERATION_FAILED);
            }

            return ret_func(1,CODE.OPERATION_SUCCESS);
          });
        }

      });

    } else {
      return ret_func(0,"非法用户");
    }
  });

}
router.get('/bindWechat', bindWechat);
router.post('/bindWechat', bindWechat);

//------------------------------------------------------------------
/* 绑定微信到已注册手机用户
 * 方式:POST
 * 参数: device:
 * 参数: uuid: 设备唯一标识(注册时的uuid)
 * 参数: userId: 用户id
 * 参数: wxuid: 微信uid
 * 参数: wxunm: 微信用户昵称
 * 参数: wxunionid 微信用户 unionid
 * */
function bindWechat2(req, res, next) {
  // get parameters
  var device = req.body.device || req.query.device;// TODO
  var uuid = req.body.uuid || req.query.uuid || '';
  var userId = Number(req.body.userId || req.query.userId || '0');
  var wxuid = req.body.wxuid || req.query.wxuid || '';
  var wxunm = req.body.wxunm || req.query.wxunm || '';
  var wxunionid = req.body.wxunionid || req.query.wxunionid || '';

  // check parameter
  if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
    return usersUtil.ret_func_json(0,"无效用户id", null, res);
  }
  if (typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
    return usersUtil.ret_func_json(0, CODE.UUID_EMPTY, null, res);
  }
  if (typeof wxuid=='undefined' || wxuid == null || wxuid.trim().length == 0){
    return usersUtil.ret_func_json(0, "无效微信用户id", null, res);
  }
  if (typeof wxunionid=='undefined' || wxunionid==null || wxunionid.trim().length == 0 ) {
    return usersUtil.ret_func_json(0, "无效unionid", null, res);
  }

  // 主用户
  var user = new ItbUserModel({
    user_id: userId,
    wechat_token: wxuid,
    wechat_nickname: wxunm,
    wechat_token_union : wxunionid
  });

  usersUtil.bindWechat(user, res, function(err, loginUser){
      if(err) {
        console.log("users.js [bindWechat2] err: " + err);
        return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, null, res);
      }
      return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, null, res);
  });
}
router.get('/bindWechat2', bindWechat2);
router.post('/bindWechat2', bindWechat2);


//------------------------------------------------------------------
/* 判断用户是否注册
 * (微信号和手机号不能全部为空; 若都不为空,优先判断手机号)
 * 方式:POST
 * 参数: device:
 * 参数: uuid: 设备唯一标识
 * 参数: mobile[可选]: 手机号
 * 参数: wxuid[可选]: 微信uid
 * */
function chkUserReg(req, res, next) {
  // get parameter
  var device = req.body.device || req.query.device;// TODO
  var uuid = req.body.uuid || req.query.uuid || '';
  var mobile = Number(req.body.mobile || req.query.mobile || '0');
  var wxuid = req.body.wxuid || req.query.wxuid || '';

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  // check parameter
  var param = {
    del_flg:0
  };

  // 无效手机号
  if (typeof mobile=='undefined' || isNaN(mobile) || mobile==null || mobile==0) {
    // 无效微信号
    if (typeof wxuid=='undefined' || wxuid == null || wxuid.trim().length == 0){
      return ret_func(0, "无效账号");
    }else {
      param.wechat_token = wxuid;
    }
  }else{
    param.mobile = mobile;
  }
  //if (typeof uuid=='undefined' || uuid == null || uuid.trim().length == 0){
  //  return ret_func(0, CODE.UUID_EMPTY);
  //}

  // 检查用户
  var chkEnt = new ItbUserModel(param);
  chkEnt.findCountFromDB(function(err, cnt){
    if(err){
      console.log('users.js [chkUserReg] check User Err: '+err);
      return ret_func(0,CODE.OPERATION_FAILED);
    }

    if(cnt>0){
      return ret_func(1,CODE.OPERATION_SUCCESS);
    } else {
      return ret_func(0,"该账号未注册");
    }
  });
}
router.get('/chkUserReg', chkUserReg);
router.post('/chkUserReg', chkUserReg);


//------------------------------------------------------------------
/* 发送验证码
 * 方式: GET
 * 参数: uuid: 设备唯一标识
 * 参数: device: 0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: mobile: 手机号
 * 参数: zone: 手机号对应区号(默认 86)
 * 返回: json对象
 * */
function sendVerCode(req, res, next) {

  var mobile = req.body.mobile || req.query.mobile || null;
  var zone = req.body.zone || req.query.zone || '86';

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  if(!mobile){
    return ret_func(0, '无效手机号！');
  }

  var redisKey = zone+'-'+mobile;
  // 检测redis
  vcdRedisCache.get(redisKey, function (error, result) {
    // 避免mobile被连续发送验证码
    var quickly = false;
    var recd = JSON.parse(result||'{}');
    if(recd && recd.vcode_mobile && recd.vcode_create_time) {
      var cur_time = Math.floor(Date.now()/1000);//process.uptime();
      if(cur_time-Number(recd.vcode_create_time||'0')<60){
        quickly = true;
      }
    }
    if(quickly){
      return ret_func(0, '您发送验证码太过频繁！');
    }

    // 发送验证码
    var url = 'http://'+CONFIG.SMS_SERVER_DOMAIN+':'+CONFIG.SMS_SERVER_PORT
        +'/itbweb/itbCom/sendVerCode.action?mobile='+mobile;
    superagent.get(url)
        .end(function(err, res2){
          if(err) {
            return ret_func(0, '验证码发送失败！');
          }

          var retJson = JSON.parse(res2.text);

          // 缓存验证码信息
          if(retJson && retJson.success==1){
            var newRecd = {
              vcode_mobile: mobile||'',
              vcode: retJson.data.code||'',
              vcode_create_time: Math.floor(Date.now()/1000),//process.uptime()
            };
            var redisValue = JSON.stringify(newRecd);
            vcdRedisCache.set(redisKey, redisValue, {ttl:60*5});// 设置失效时间5分钟

            return ret_func(1, '成功');

          } else {
            return ret_func(0, '发送失败');
          }
        });
  });
}
router.post('/sendVerCode', sendVerCode);
router.get('/sendVerCode', sendVerCode);

//------------------------------------------------------------------
/* 验证验证码
 * 方式: GET
 * 参数: device: 请求来源
 * 参数: uuid: 设备唯一标识
 * 参数: zone: 手机号对应区号(默认 86)
 * 参数: mobile: 手机号
 * 参数: code: 验证码
 * 返回: JSON对象
 {
   "success":1,
   "msg":"成功",
 }
 * */
function checkVerCode(req, res, next) {

  var mobile = req.body.mobile || req.query.mobile || null;
  var uuid = req.body.uuid || req.query.uuid || null;
  var zone = req.body.zone || req.query.zone || '86';
  var vcode = req.body.code || req.query.code || null;

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  if(!mobile){
    return ret_func(0, '无效手机号！');
  }
  if(!uuid){
    return ret_func(0, '无效uuid！');
  }
  if(!vcode){
    return ret_func(0, '无效验证码！');
  }

  var redisKey = zone+'-'+mobile;
  // 检查redis
  vcdRedisCache.get(redisKey, function (error, result) {
    var recd = JSON.parse(result||'{}');
    if(!recd.vcode){
      return ret_func(0, '尚未获取验证码(或验证码已失效)！');
    }
    if(recd.vcode != vcode){
      return ret_func(0, '验证码错误！');
    }
    if(recd.vcode_mobile != mobile){
      return ret_func(0, '验证码与手机号不匹配！');
    }

    // 比较时间，如果超过5分钟，则返回失败
    // 比较 vcode_create_time 和当前时间
    var cur_time = Math.floor(Date.now()/1000);//process.uptime();
    if(cur_time-Number(recd.vcode_create_time||'0')>=5*60){
      return ret_func(0, '验证码已失效，请重新获取！');
    }

    return ret_func(1, CODE.OPERATION_SUCCESS);
  });
}
router.post('/checkVerCode', checkVerCode);
router.get('/checkVerCode', checkVerCode);

//------------------------------------------------------------------
/* 组织用户数据
 * 参数: platformRecds(包含itb_user数据的itb_platform_user数据)
 * 返回值:
  {
    "userId":1055,
        "userType":1,
        "mobile":13297922921,
        "registerUUID":"QWERTYUIOP-iOS",
        "nickName":"哈哈",
        "headUrl":"http://www.itbour.com/header/xxx.png",
        "userSign":"我就是不写签名咋地了",
        "accessory":[
      {
        "platform":1,
        "nickName":"平台一昵称",
        "headerUrl":"平台一头像",
        "field1":"平台一字段一",
        "field2":"平台一字段二",
        "field3":"平台一字段三",
        "field4":"平台一字段四",
        "field5":"平台一字段五"
      }
    ]
  }
**/
function initOrganizeUserInfo(userItem){
  return {
    userId: userItem.user_id,
    userType: userItem.user_type,
    mobile: userItem.mobile,
    registerUUID: userItem.uuid||'',
    nickName: userItem.nickname||'',
    headerUrl: userItem.head_url||'http://itbour-back.oss-cn-hangzhou.aliyuncs.com/app/default_head.png',
    userSign: userItem.signature||'',
    accessory: []
  };
}
function  organizeUserInfo(items) {
  var retData = null;

  if(items && items.length>0) {
    retData = initOrganizeUserInfo(items[0]);

    for(var i=0; i<items.length; i++){
      retData.accessory.push({
        "platform": items[i].platform,
        "nickName": items[i].p_nickname||'',
        "headerUrl": items[i].p_head_url||'',
        "field1": items[i].field1||'',
        "field2": items[i].field2||'',
        "field3": items[i].field3||'',
        "field4": items[i].field4||'',
        "field5": items[i].field5||'',
      });
    }
  }

  return retData;
}

//------------------------------------------------------------------
/* 验证验证码并登录
 * 方式: GET
 * 参数: uuid: 设备唯一标识
 * 参数: device: 0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: mobile: 手机号
 * 参数: zone: 手机号对应区号(默认 86)
 * 参数: code: 验证码
 * 返回: JSON对象
   {
     "success":1,
     "msg":"成功",
     "data":{
       "userId":1055,
       "userType":1,
       "mobile":13297922921,
       "registerUUID":"QWERTYUIOP-iOS",
       "nickName":"哈哈",
       "headUrl":"http://www.itbour.com/header/xxx.png",
       "userSign":"我就是不写签名咋地了",
       "accessory":[
         {
         "platform":1,
         "nickName":"平台一昵称",
         "headerUrl":"平台一头像",
         "field1":"平台一字段一",
         "field2":"平台一字段二",
         "field3":"平台一字段三",
         "field4":"平台一字段四",
         "field5":"平台一字段五"
         }
       ]
     }
   }
 * */
var DEFAULT_TEST_MOBILE_FOR_CHECK="18696138681";
var DEFAULT_TEST_MOBILE_FOR_CHECK2="18256276313";
var DEFAULT_TEST_VCODE_FOR_CHECK="123456";
function loginByVerCode(req, res, next) {

  var mobile = req.body.mobile || req.query.mobile || null;
  var uuid = req.body.uuid || req.query.uuid || null;
  var zone = req.body.zone || req.query.zone || '86';
  var vcode = req.body.code || req.query.code || null;

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  if(!mobile){
    return ret_func(0, '无效手机号！');
  }
  if(!uuid){
    return ret_func(0, '无效uuid！');
  }
  if(!vcode){
    return ret_func(0, '无效验证码！');
  }

  var redisKey = zone+'-'+mobile;
  // 检查redis
  vcdRedisCache.get(redisKey, function (error, result) {
    if(mobile==DEFAULT_TEST_MOBILE_FOR_CHECK || mobile==DEFAULT_TEST_MOBILE_FOR_CHECK2){
      if(vcode != DEFAULT_TEST_VCODE_FOR_CHECK){
        return ret_func(0, '验证码错误');
      }
    }else{
      var recd = JSON.parse(result||'{}');
      if(!recd.vcode){
        return ret_func(0, '尚未获取验证码(或验证码已失效)！');
      }
      if(recd.vcode != vcode){
        return ret_func(0, '验证码错误！');
      }
      if(recd.vcode_mobile != mobile){
        return ret_func(0, '验证码与手机号不匹配！');
      }

      // 比较时间，如果超过5分钟，则返回失败
      // 比较 vcode_create_time 和当前时间
      var cur_time = Math.floor(Date.now()/1000);//process.uptime();
      if(cur_time-Number(recd.vcode_create_time||'0')>=5*60){
        return ret_func(0, '验证码已失效，请重新获取！');
      }

    }


    // 处理
    usersUtil.findInsertUser(mobile, uuid, function(error, userItem){
      if(error){
        return ret_func(0, CODE.OPERATION_FAILED);
      }
      if(!userItem){
        return ret_func(0, CODE.OPERATION_FAILED);
      }
      // get user info
      var entity = new ItbUserModel({
        mobile: mobile
      });
      entity.findWithPlatformInfo(function(error, items){
        if(error){
          console.log('users.js[loginByVerCode] findWithPlatformInfo error: '+error);
          return ret_func(0, CODE.OPERATION_FAILED);
        }

        if (items != null && items.length > 0) {
          var retData = organizeUserInfo(items);
          return ret_func(1, CODE.OPERATION_SUCCESS, retData);

        } else {
          var retData = initOrganizeUserInfo(userItem);
          return ret_func(1, CODE.OPERATION_SUCCESS,retData);
        }
      });
    })

  });
}
router.post('/loginByVerCode', loginByVerCode);
router.get('/loginByVerCode', loginByVerCode);

//------------------------------------------------------------------
/* 验证第三方账户, 若已关联手机号, 则直接登录; 否则, 关联手机号
 * 方式: GET
 * 参数: device: 请求来源
 * 参数: uuid: 设备唯一标识
 * 参数: platform: 1微信, 2小米
 * 参数: info: {field1:xxx, field2:xxx, field3:xxx, field4:xxx, field5:xxx}
 * 返回: JSON对象(参照loginByVerCode)
 * */
function loginByPlatformUser(req, res, next) {

  var info = req.body.info || req.query.info || {};
  var platform = Number(req.body.platform || req.query.platform || '0');

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }


  if(platform<=0){
    return ret_func(0, '未知平台用户！');
  }
  if(!info || !info.field1){
    return ret_func(0, '参数错误！');
  }

  // check user info
  var param = {
    platform: platform,
  };
  if(platform == 1) {// 微信
    param.field1 = info.field1||'';// 微信unionId

  } else if(platform == 2) {// 小米
    param.field1 = info.field1||'';// 小米userId
  }

  var entity = new ItbUserModel(param);
  entity.findWithPlatformInfo(function(error, items){
    if(error){
      console.log('users.js[loginByPlatformUser] findWithPlatformInfo error: '+error);
      return ret_func(0, CODE.OPERATION_FAILED);
    }

    if (items != null && items.length > 0) {// 已经绑定手机
      var retData = organizeUserInfo(items);
      return ret_func(1, CODE.OPERATION_SUCCESS, retData);

    } else {// 未绑定手机
      return ret_func(1, CODE.OPERATION_SUCCESS,{});
    }
  });
}
router.post('/loginByPlatformUser', loginByPlatformUser);
router.get('/loginByPlatformUser', loginByPlatformUser);

//------------------------------------------------------------------
/* 第三方账户绑定手机号（第三方账户首次登录）
 * 方式: GET
 * 参数: device: 请求来源
 * 参数: uuid: 设备唯一标识
 * 参数: mobile: 手机号
 * 参数: zone: 手机号对应区号(默认 86)
 * 参数: code: 验证码
 * 参数: platform: 1微信, 2小米
 * 参数: info: {field1:xxx, field2:xxx, field3:xxx, field4:xxx, field5:xxx, nickname:xxx, headurl:xxx}
 * 返回: JSON对象(参照verCodeLogin)
 * */
function bindPlatformUser(req, res, next) {

  var uuid = req.body.uuid || req.query.uuid || null;
  var mobile = req.body.mobile || req.query.mobile || null;
  var zone = req.body.zone || req.query.zone || '86';
  var vcode = req.body.code || req.query.code || null;
  var info = req.body.info || req.query.info || {};
  var platform = req.body.platform || req.query.platform || null;

  // return function
  function ret_func(success, msg, data){
    var obj = {
      success:success,
      msg:msg,
      data:data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
  }

  if(!mobile){
    return ret_func(0, '无效手机号！');
  }
  if(!uuid){
    return ret_func(0, '无效uuid！');
  }
  if(!vcode){
    return ret_func(0, '无效验证码！');
  }
  if(!platform){
    return ret_func(0, '未知平台用户！');
  }
  if(!info || !info.field1){
    return ret_func(0, '参数错误！');
  }

  var redisKey = zone+'-'+mobile;
  // 检查redis
  vcdRedisCache.get(redisKey, function (chkErr, chkRet) {
    if(mobile==DEFAULT_TEST_MOBILE_FOR_CHECK){
      if(vcode != DEFAULT_TEST_VCODE_FOR_CHECK){
        return ret_func(0, '验证码错误');
      }
    }else{
      var recd = JSON.parse(chkRet || '{}');
      if (!recd.vcode) {
        return ret_func(0, '尚未获取验证码(或验证码已失效)！');
      }
      if (recd.vcode != vcode) {
        return ret_func(0, '验证码错误！');
      }
      if (recd.vcode_mobile != mobile) {
        return ret_func(0, '验证码与手机号不匹配！');
      }

      // 比较时间，如果超过5分钟，则返回失败
      // 比较 vcode_create_time 和当前时间
      var cur_time = Math.floor(Date.now()/1000);//process.uptime();
      if (cur_time - Number(recd.vcode_create_time || '0') >= 5 * 60) {
        return ret_func(0, '验证码已失效，请重新获取！');
      }
    }



    // 处理
    usersUtil.findInsertUser(mobile, uuid, function(err, userItem){
      if(err){
        return ret_func(0, CODE.OPERATION_FAILED);
      }
      if(!userItem){
        return ret_func(0, CODE.OPERATION_FAILED);
      }
      // get user info
      var entity = new ItbUserModel({
        mobile: mobile,
        platform: platform,
      });
      entity.findWithPlatformInfo(function(error, items){
        if(error){
          console.log('users.js[bindPlatformUser] findWithPlatformInfo error: '+error);
          return ret_func(0, CODE.OPERATION_FAILED);
        }

        if (items != null && items.length > 0) {// 已经绑定
          // 直接返回
          var retData=organizeUserInfo(items);
          return ret_func(1, CODE.OPERATION_SUCCESS, retData);

        } else {// 未绑定
          // 新规platform_user
          var newEnt = new ItbPlatformUserModel({
            user_id: userItem.user_id,
            platform: platform,
            field1: info.field1||'',
            field2: info.field2||'',
            field3: info.field3||'',
            field4: info.field4||'',
            field5: info.field5||'',
            nickname: info.nickname||'',
            head_url: info.headurl||'',
            update_by: userItem.user_id,
          });
          newEnt.saveToDB(function(saveErr, newId){
            if(saveErr){
              console.log('users.js[bindPlatformUser] save platform_user Err: '+saveErr);
              return ret_func(0, CODE.OPERATION_FAILED);
            }

            // 重新获取信息
            var gerEnt = new ItbUserModel({
              user_id: userItem.user_id,
            });
            gerEnt.findWithPlatformInfo(function(error2, items2) {
              if (error2) {
                console.log('users.js[bindPlatformUser] findWithPlatformInfo_2 Err: ' + error2);
                return ret_func(0, CODE.OPERATION_FAILED);
              }

              if (items2 != null && items2.length > 0) {
                var retData = organizeUserInfo(items2);
                return ret_func(1, CODE.OPERATION_SUCCESS, retData);

              } else {
                var retData = initOrganizeUserInfo(userItem);
                return ret_func(1, CODE.OPERATION_SUCCESS,retData);
              }
            });
          });
        }

      });
    })

  });

}
router.post('/bindPlatformUser', bindPlatformUser);
router.get('/bindPlatformUser', bindPlatformUser);

//------------------------------------------------------------------
/* 获取用户作品列表
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 uuid: 设备标识符
 * 参数 userId: 用户唯一标识
 * 参数 typeL: 0 未分类(返回所有); 1 海报; 2 多页; 3 ppt; 4 印品
 * 参数 pageNum: 请求页号(0开始 )
 * 参数 pageSize: 请求页大小
 * 参数 withTotalPage[可选] 0, 标示不获取总页数, 1 标识获取总页数
   {
     "success":1,
     "msg":"成功",
     "data":{
       "list":[
         {
           "id":989,
           "thumb":"http://oss-itbour.com-osss",
           "title":"作品名称",
           "typeL":1,
           "time":"2016-12-15 15:30"
         },
         {
           "id":989,
           "thumb":"http://oss-itbour.com-osss",
           "title":"作品名称",
           "typeL":1,
           "time":"2016-12-15 15:30"
         }
       ]
     }
   }
   测试地址: http://localhost:3000/users/getUserDocs?device=1&userId=128685&typeL=0&pageNum=0&pageSize=10&uuid=1&withTotalPage=1
 * */
// todo 修改接口, 增加 withTotalPage 可选参数, 已实现, 待审核 begin
function getUserDocs(req, res, next) {
  var device = checkUtil.stringFromReq(req, 'device');
  if(!device) {
    return usersUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
  }
  var uuid = checkUtil.stringFromReq(req, 'uuid');
  if(!uuid) {
    return usersUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
  }
  var userId = checkUtil.numberFromReq(req, 'userId');
  if(!userId) {
    return usersUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
  }
  var typeL = checkUtil.numberFromReq(req, 'typeL');
  var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
  var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 0;
  var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage');

  // 根据大分类查找用户文档
  usersUtil.get_UserDocs(userId, typeL, pageNum, pageSize, function(error, result){
    if(error){
      console.log(error);
      return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
    }

    var retData =[];
    if(result && result.length>0) {
      for (var i = 0; i < result.length; i++) {
        retData.push({
          id: result[i].doc_id,
          thumb: result[i].thumb || '',
          title: result[i].doc_name || '',
          typeL: result[i].top_type || 0,
          time: (new moment(result[i].create_time)).format('YYYY-MM-DD HH:mm'),
        });
      }
    }

    var data = {list:retData, currentPage : pageNum};
    // 获取总页数
    if(withTotalPage) {
      usersUtil.get_UserDocsCnt(userId, typeL, pageNum, pageSize, function(error1, count){
        if(error){
          console.log(error);
          return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
        }
        var totalPage = Math.floor((count-1)/pageSize)+1;
        data.totalPage = totalPage;
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
      });
    } else {
      return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    }

  });

}
router.get('/getUserDocs', getUserDocs);
router.post('/getUserDocs', getUserDocs);
// todo 修改接口, 增加 withTotalPage 可选参数, 已实现, 待审核 begin

//------------------------------------------------------------------
/* 重命名作品名称
 * 方式:POST
 * 参数 device: 0:PC, 1:iOS, 2:android
 * 参数 uuid: 设备标识符
 * 参数 userId: 用户唯一标识
 * 参数 typeL: 0 未分类(错误); 1 海报; 2 多页; 3 ppt; 4 印品
 * 参数 id: 文档id
 * 参数 name: 文档名
   {
     "success":1,
     "msg":"成功",
     "data":{}
   }
 * */
function renameDoc(req, res, next) {
  var device = checkUtil.stringFromReq(req, 'device');
  if(!device) {
    return usersUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
  }
  var uuid = checkUtil.stringFromReq(req, 'uuid');
  if(!uuid) {
    return usersUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
  }
  var userId = checkUtil.numberFromReq(req, 'userId');
  if(!userId) {
    return usersUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
  }
  var typeL = checkUtil.numberFromReq(req, 'typeL') || 0;
  /**
   *
   // 1.单页  2.多页  3.ppt  4.印品  6.社交媒体  7.电商  8.微商 1010. logo 1011 营销商品
   CONFIG.DOC_TYPE_1 = 1;
   CONFIG.DOC_TYPE_2 = 2;
   CONFIG.DOC_TYPE_3 = 3;
   CONFIG.DOC_TYPE_4 = 4;
   CONFIG.DOC_TYPE_6 = 6;
   CONFIG.DOC_TYPE_7 = 7;
   CONFIG.DOC_TYPE_8 = 8;
   CONFIG.DOC_TYPE_1010 = 1010;
   CONFIG.DOC_TYPE_1011 = 1011;
   * */
  if( typeL != CONFIG.DOC_TYPE_1 &&
      typeL != CONFIG.DOC_TYPE_2 &&
      typeL != CONFIG.DOC_TYPE_3 &&
      typeL != CONFIG.DOC_TYPE_4 &&
      typeL != CONFIG.DOC_TYPE_6 &&
      typeL != CONFIG.DOC_TYPE_7 &&
      typeL != CONFIG.DOC_TYPE_8 &&
      typeL != CONFIG.DOC_TYPE_1010) {
    return usersUtil.ret_func_json(0,'无效分类',{},res);
  }
  var docId = checkUtil.numberFromReq(req, 'id');
  if(!docId) {
    return usersUtil.ret_func_json(0,'文档ID为空',{},res);
  }
  var docName = checkUtil.stringFromReq(req, 'name')||'';

  // 重命名用户文档
  usersUtil.renameUserDoc(userId, typeL, docId, docName, function(error, result){
    if(error){
      console.log(error);
      return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
    }

    return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{},res);
  });
}
router.get('/renameDoc', renameDoc);
router.post('/renameDoc', renameDoc);



//------------------------------------------------------------------
/* 提交设计师合作信息
 * 方式: GET
 * 参数: device	0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: info	{
 *                  "organize":"武汉示界港科技有限公司",
 *                  "name":"呵呵哒","
 *                  mobile":13037148601,
 *                  "email":"123@qq.com",
 *                  "qq":123456789
 *               }
 * 返回结果	{"success":1,"msg":"成功","data":{id:123}}
 * 测试地址：http://localhost:3000/users/applyPartner?device=1&uuid=2&userId=13&orderId=5&info={%22organize%22:%22%E6%AD%A6%E6%B1%89%E7%A4%BA%E7%95%8C%E6%B8%AF%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22name%22:%22%E5%91%B5%E5%91%B5%E5%93%92%22,%22mobile%22:13037148601,%22email%22:%22123@qq.com%22,%22qq%22:123456789}
 * */
function applyPartner(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return usersUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return usersUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return usersUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var info = checkUtil.stringFromReq(req, 'info');
    if(!info) {
        return usersUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }else{
        info = JSON.parse(info);
    }

    // CONFIG.APPLY_TO_BE_PARTNER_TIME_LIMIT 提交申请间隔, 单位 秒
    usersUtil.applyPartner(userId,info,CONFIG.APPLY_TO_BE_PARTNER_TIME_LIMIT, function(error,id){
        if(error){
            console.log(error);
            return usersUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(!id){
            var msg = "不能申请太频繁，请"+CONFIG.APPLY_TO_BE_PARTNER_TIME_LIMIT/60+"分钟后重新提交";
            return usersUtil.ret_func_json(0,msg,{},res);
        }

        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{id:id},res);
    });


}
router.post('/applyPartner', applyPartner);
router.get('/applyPartner', applyPartner);




//------------------------------------------------------------------
/* 删除用户作品
 * 方式: GET
 * 参数: device	0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: typeL	0 未分类(错误) 1 海报  2 多页  3 ppt.  4. 印品
 * 参数: id	 作品 id
 * 返回结果	{"success":1,"msg":"成功","data":{}}
 * 测试地址：http://localhost:3000/users/removeDoc?device=1&uuid=2&userId=13&id=48223&typeL=3
 * */
function removeDoc(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return usersUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return usersUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return usersUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var typeL = checkUtil.numberFromReq(req, 'typeL');
    if(!typeL) {
        return usersUtil.ret_func_json(0,CODE.TYPE_L_EMPTY,{},res);
    }
    var id = checkUtil.numberFromReq(req, 'id');
    if(!id) {
        return usersUtil.ret_func_json(0,CODE.DOC_ID_EMPTY,{},res);
    }


    usersUtil.removeDoc(userId, typeL,id, function(error){
        if(error){
            console.log(error);
            return usersUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }


        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });


}
router.post('/removeDoc', removeDoc);
router.get('/removeDoc', removeDoc);


//------------------------------------------------------------------
/* 获取用户订单对应的印品作品预览图
 * 方式: GET
 * 参数: device	0表示从pc来的请求1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	 商品订单 id
 * 返回结果:
 * {
 * 	    "success":1,
 * 	    "msg":"成功",
 * 	    "data":{
 * 	        "productInfo":[
 * 	            {
 * 	                "id":345,
 * 	                "detailOrderId":1,
 * 	                "previews":[
 * 	                    "http://oss-image.jpg",
 * 	                    "http://oss-image.jpg"
 * 	                ]
 * 	            }
 * 	        ]
 * 	    }
 * 	}
 * 测试地址：http://localhost:3000/users/getDocPreviewByOrder?device=1&uuid=2&userId=78849&id=1&orderId=34
 * */
function getDocPreviewByOrder(req, res, next) {

    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return usersUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return usersUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return usersUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return usersUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    usersUtil.getDocPreviewByOrder(userId, orderId, function(error, data){
        if(error){
            console.log(error);
            return usersUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }


        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{productInfo:data},res);
    });


}
router.post('/getDocPreviewByOrder', getDocPreviewByOrder);
router.get('/getDocPreviewByOrder', getDocPreviewByOrder);

////------------------------------------------------------------------
///* 测试
// * 测试地址：http://localhost:3000/users/test_exchgCouponAndTryAddPartnerCustom?mobile=18696138681
// * */
//function test_exchgCouponAndTryAddPartnerCustom(req, res, next) {
//
//    var mobile = checkUtil.numberFromReq(req, 'mobile') || 18696138681;
//    if(!mobile) {
//        return usersUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
//    }
//
//    usersUtil.exchgCouponAndTryAddPartnerCustom(mobile, function(error, data){
//        if(error){
//            console.log(error);
//            return usersUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
//        }
//        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
//    });
//
//
//}
//router.post('/test_exchgCouponAndTryAddPartnerCustom', test_exchgCouponAndTryAddPartnerCustom);
//router.get('/test_exchgCouponAndTryAddPartnerCustom', test_exchgCouponAndTryAddPartnerCustom);


//------------------------------------------------------------------
module.exports = router;
